<?php
namespace weixin\mp;

require_once "helper.php";
require_once "access_token.php";

class msg_sender {

	private $access_token;

	public function __construct() {
		$this -> access_token = new access_token();
	}

	/**
	 * 在请求的企业微信接口后面自动附加token信息
	 */
	private function append_token($url) {
		$token = $this -> access_token -> get_access_token();

		if (strrpos($url, "?", 0) > -1) {
			return $url . "&access_token=" . $token;
		} else {
			return $url . "?access_token=" . $token;
		}
	}

	public function send($data) {
		$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
		$ret = http_post($this -> append_token($url), $data);
		return $ret["content"];
	}

	//  $info = array();
	//$info["media"] = '@' . $tmp_file . ".csv";

	public function upload_media($media_path, $type) {
		$url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?type=' . $type;

		$data['media'] = '@' . $media_path;

		$result = http_post($this -> append_token($url), $data, true);
		$result = $result["content"];
		if ($result) {
			$json = json_decode($result, true);
			if (!$json || !empty($json['errcode'])) {
				$this -> errCode = $json['errcode'];
				$this -> errMsg = $json['errmsg'];
				return false;
			}
			return $json;
		}
		return false;
	}

	public function create_menu($menu) {
		$url = 'https://api.weixin.qq.com/cgi-bin/menu/create';
		$ret = http_post($this -> append_token($url), $menu);
		return $ret["content"];
	}

	public function create_qrcode($data) {
		$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create';
		$ret = http_post($this -> append_token($url), $data);
		return $ret["content"];
	}

}
